<template>
    <van-sticky>
        <van-nav-bar
            title="修改收货地址"
            left-text="返回"
            left-arrow
            @click-left="onBack"
        />
    </van-sticky>

    <van-address-edit
        :area-list="areaList"
        :address-info="AddressInfo"
        show-set-default
        show-delete
        :area-columns-placeholder="['请选择', '请选择', '请选择']"
        @save="onSave"
        @delete="onDelete"
    />
</template>

<script setup>
import { areaList } from '@vant/area-data';
const { proxy } = getCurrentInstance();

const business = proxy.$business;
const id = ref(proxy.$route.query.id);
const AddressInfo = ref({});

onBeforeMount(() => {
    getAddressInfo();
})

const getAddressInfo = async () =>
{
    let params = {
        id:id.value,
        busid:business.value.id
    }

    let result = await proxy.$http.post({
        url:'/address/info',
        params
    })

    if(result.code === 1)
    {
        let info = result.data;

        AddressInfo.value = {
            name:info.consignee,
            tel:info.mobile,
            areaCode:info.district ? info.district : (info.city ? info.city : info.province),
            addressDetail:info.address,
            isDefault:info.status == 1 ? true : false
        }

    }else{
        proxy.$warning({
            message:result.msg,
            onClose:() =>
            {
                onBack();
            }
        });
    }
}

const onDelete = () =>
{
    proxy.$confirm({
        title:'删除',
        message:'是否确认删除该收货地址？'
    }).then(async () => {
        let params = {
            id:id.value,
            busid:business.value.id
        }
        
        let result = await proxy.$http.post({
            url:'/address/del',
            params
        })

        if(result.code === 1)
        {
            proxy.$success({
                message:result.msg,
                onClose:() =>
                {
                    onBack();
                }
            });
        }else{
            proxy.$warning(result.msg);
        }
    }).catch(() => {});

}


const onSave = async (values) =>
{
    let params = {
        id:id.value,
        busid:business.value.id,
        consignee:values.name,
        mobile:values.tel,
        code:values.areaCode,
        address:values.addressDetail,
        status:values.isDefault === true ? 1 : 0
    }
    
    let result = await proxy.$http.post({
        url:'/address/edit',
        params
    });

    if(result.code === 1)
    {
        proxy.$success({
            message:result.msg,
            onClose:() =>
            {
                onBack();
            }
        });
    }else{
        proxy.$warning(result.msg);
    }
}

const onBack = () => proxy.$router.back();
</script>